﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kooboo.HtmlFunc;
using Kooboo.HtmlFunc.Providers;
using Kooboo.CMS.SiteConverter.Models;

namespace Kooboo.CMS.SiteConverter.Parser.Razor
{
    public class ViewPartParser : ParserBase, IParser<IViewPart>
    {
        public static void FillResult(ParserContext context, IViewPart obj,
            string engineName, IReplacement replacement = null, Kooboo.CMS.Sites.Models.DataRuleSetting dataRuleSetting = null)
        {
            // view
            var view = new CmsView();
            view.EngineName = engineName;
            view.Name = obj.ViewName;
            var body = NodeExtension.ReadString(obj.StartNode, obj.EndNode, !ParserSetting.RemoveFuncMarkers);
            view.Body = (replacement != null) ? replacement.Replace(body) : body;
            if (dataRuleSetting != null)
                view.DataRules.Add(dataRuleSetting);

            // view position
            if (obj.OwnerPosition != null)
            {
                context.Result.Page.PagePositions.Add(new Kooboo.CMS.Sites.Models.ViewPosition()
                {
                    ViewName = view.Name,
                    LayoutPositionId = obj.OwnerPosition.Name,
                    Order = obj.Order.HasValue ? obj.Order.Value : 0
                });
            }

            // fill view
            context.Result.Views.Add(view);
        }

        #region IParser<IViewPart> Members

        public void Parse(IViewPart obj)
        {
            FillResult(this.Context, obj, this.EngineName);
        }

        #endregion
    }

    public interface IReplacement
    {
        string Replace(string str);
    }

    public class Replacement : IReplacement
    {
        public string From
        {
            get;
            set;
        }

        public string To
        {
            get;
            set;
        }

        public string Replace(string str)
        {
            return str.Replace(this.From, this.To);
        }
    }
}
